/**
 * Created with IntelliJ IDEA.
 * User: vuntermann
 * Date: 20/05/13
 * Time: 19:30
 * To change this template use File | Settings | File Templates.
 */
class Ticket {

    Map ticketDetails

    int subTotal

    int total

    Ticket(){
        this.ticketDetails = [:]
    }
    
    def hasProduct(product) {
        ticketDetails[product] != null
    }

    def add(product) {
        if (!hasProduct(product)) {
            ticketDetails[product] = new TicketDetail()
        }
        else {
            TicketDetail ticketDetail = ticketDetails[product]
            ticketDetail.increaseCount()
        }
    }

    def int getTotalDiscount(Map promotions, Map priceList){
        calculateDiscounts(promotions, priceList)
        def total = 0
        ticketDetails.keySet().each{total += ticketDetails[it].productDiscount}
        return total
    }



    void calculateDiscounts(Map promotions, Map priceList) {
       for(product in ticketDetails.keySet()){
            TicketDetail ticketDetailProduct = ticketDetails[product]
            Promotion promotion = promotions[product]
            if(has(promotion)){
                Integer promotionCount = ticketDetailProduct.productCount / promotion.countOfProducts
                ticketDetailProduct.productDiscount = ((priceList[product] * ticketDetailProduct.productCount) - promotion.price) * promotionCount
            } else {
                ticketDetailProduct.productDiscount = 0
            }
        }
    }

    private boolean has(Promotion promotion) {
        promotion != null
    }

    Integer countOfProduct(product) {
        !(hasProduct(product)) ? 0 : this.ticketDetails[product].productCount
    }
}
